package br.net.woodstock.tickettoride.struts2.web.security;

import java.util.Enumeration;

import javax.servlet.http.HttpSession;

import br.net.woodstock.rockframework.web.struts2.utils.Struts2Utils;
import br.net.woodstock.tickettoride.orm.User;
import br.net.woodstock.tickettoride.orm.UserType;

public abstract class SecurityUtils {

	private SecurityUtils() {
		//
	}

	public static User getSessionUser() {
		HttpSession session = Struts2Utils.getSession();
		User user = (User) session.getAttribute(Constants.USER_ATTRIBUTE);
		if (user != null) {
			return user;
		}
		return null;
	}

	public static void setSessionUser(final User user) {
		HttpSession session = Struts2Utils.getSession();
		if (user != null) {
			session.setAttribute(Constants.USER_ATTRIBUTE, user);
		} else {
			session.removeAttribute(Constants.USER_ATTRIBUTE);
			session.invalidate();
		}
	}

	@SuppressWarnings("rawtypes")
	public static void invalidateSession() {
		HttpSession session = Struts2Utils.getSession();
		Enumeration e = session.getAttributeNames();

		while (e.hasMoreElements()) {
			String s = e.nextElement().toString();
			session.removeAttribute(s);
		}
		session.invalidate();
	}

	public static boolean isLoggedIn() {
		User user = SecurityUtils.getSessionUser();
		if (user != null) {
			return true;
		}
		return false;
	}

	public static boolean isUserInRole(final String role) {
		User user = SecurityUtils.getSessionUser();
		if (user != null) {
			UserType type = user.getType();
			if (type != null) {
				if (type.name().equalsIgnoreCase(role)) {
					return true;
				}
			}
		}
		return false;
	}

}
